﻿namespace EFS.RC.SupervisorCentral.Common.Config.Sections.Monitoring.Thresholds
{
	public class Limits
	{
		System.String name = null;
		private System.Int32 left = -1;
		private System.Int32 right = -1;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="keyName"></param>
		public Limits( System.String keyName)
		{
			// check
			EFS.Common.Verify.String(keyName, "keyName");

			// hey name
			this.name = keyName;
			
			// load
			Load();
		}

		/// <summary>
		/// Left
		/// </summary>
		public System.Int32 Left
		{
			get { return left; }
			set
			{
				left = value;
				Save();
			}
		}

		/// <summary>
		/// Right
		/// </summary>
		public System.Int32  Right
		{
			get { return right; }
			set 
			{ 
				right = value;
				Save();
			}
		}

		/// <summary>
		/// Save
		/// </summary>
		private void Save()
		{
			// left right
			System.String limitValue = System.String.Format("{0}:{1}", left, right); 

			// get cnfig
			System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);

			// get filter phones
			System.Configuration.KeyValueConfigurationElement limitEntry = config.AppSettings.Settings[name];
			if (null == limitEntry)
			{
				limitEntry = new System.Configuration.KeyValueConfigurationElement("limit", limitValue);
				config.AppSettings.Settings.Add(limitEntry);
			}
			else
			{
				limitEntry.Value = limitValue;
			}

			// save & reresh
			config.Save(System.Configuration.ConfigurationSaveMode.Modified);
			System.Configuration.ConfigurationManager.RefreshSection("appSettings");
		}

		/// <summary>
		/// Load
		/// </summary>
		private void Load()
		{
			// get value
			System.String keyValue = System.Configuration.ConfigurationManager.AppSettings[name];

			// check
			if (EFS.Common.Verify.String(keyValue))
			{
				// get value
				System.String[] values = keyValue.Split(new System.Char[] { ':' }, System.StringSplitOptions.RemoveEmptyEntries);

				// parse
				System.Int32.TryParse(values[0], out left);
				System.Int32.TryParse(values[1], out right);
			}
		}
	}

}